package com.woniuxy02;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 作者
 * @create 2025-11-18 16:07
 */
public class Test02 {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Map<String, Object> map=new HashMap<>();
        map.put("sid", 1);
        map.put("sname", "zs");
//        map.put("age", 12);
        map.put("x", "xxx");
        map.put("y", "yyy");

        Student student = mapToBean(map, Student.class);
        System.out.println(student);

        Teacher teacher = mapToBean(map, Teacher.class);
        System.out.println(teacher);

    }


    //写一个通用方法，将map转任意对象
    // 泛型类 泛型接口 泛型方法
    public static <T> T mapToBean(Map<String,Object> map,Class<T> clazz) throws InstantiationException, IllegalAccessException {
        //创建对象
        T t = clazz.newInstance();
        //反射赋值
        for(Field field :  clazz.getDeclaredFields()){
            if(map.containsKey(field.getName())){
                field.setAccessible(true);
                field.set(t,map.get(field.getName()));
            }
        }
        return t;
    }


    private static void test01() throws InstantiationException, IllegalAccessException {
        Map<String, Object> map=new HashMap<>();

        map.put("sid", 1);
        map.put("sname", "zs");
//        map.put("age", 12);
        map.put("x", "xxx");
        map.put("y", "yyy");

        Class clazz = Student.class;
        Student student = (Student) clazz.newInstance();
        //将map中的key和对象的属性名，能够对应，使用value给对应的属性赋值

//        for(Field field :  clazz.getDeclaredFields()){
//            for( String key : map.keySet()){
//                if(field.getName().equals(key)){
//                    field.setAccessible(true);
//                    field.set(student,map.get(key));
//                }
//            }
//        }
        for(Field field :  clazz.getDeclaredFields()){
            if(map.containsKey(field.getName())){
                field.setAccessible(true);
                field.set(student,map.get(field.getName()));
            }
        }
        System.out.println(student);
    }
}
